package com.eshop.dao;

import com.eshop.domain.Category;
import com.eshop.domain.Product;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by Sergey on 17.12.13.
 */
public class ProductDao extends HibernateUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductDao.class);

    public List<Product> load() {
        Session session = null;
        try {
            session = getSessionFactory().openSession();
            return session.createCriteria(Product.class).list();
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return null;
    }

    public List<Product> loadByCategories(List<Category> categories) {
        Session session = null;
        try {
            session = getSessionFactory().openSession();
            return session.createCriteria(Product.class)
                    .add(Restrictions.in("category", categories)).list();
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return null;
    }

    public Product getById(Long id) {
        Session session = null;
        try {
            session = getSessionFactory().openSession();
            return (Product) session.load(Product.class, id);
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return null;
    }
}
